"use strict";

import clear from 'rollup-plugin-clear';
import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import typescript from 'rollup-plugin-typescript2';
import screeps from 'rollup-plugin-screeps';
import { wasm } from '@rollup/plugin-wasm';
import copy from 'rollup-plugin-copy'
import path from 'path';
// let  cfg = require("./screeps.json")
let cfg;
if (!process.env.DEST) console.log("未指定目标, 代码将被编译但不会上传")
else if (!(cfg = require("./screeps.json")[process.env.DEST])) {
    throw new Error("无效目标,请检查 secret.json 中是否包含对应配置")
}
console.log(JSON.stringify(cfg));
const pluginDeploy = cfg && cfg.copyPath ?
// 复制到指定路径
copy({
    targets: [
        {
            src: 'src/lib/LayoutCal_mod.js',
            dest: 'dist',
        },
        {
            src: 'src/lib/wasm_loader.js',
            dest: 'dist',
        },
        {
            src: 'src/lib/Analysis.js',
            dest: 'dist',
        },
        {
            src: 'src/lib/LayoutCal.wasm',
            dest: 'dist',
        },
        {
            src: 'src/lib/Analysis.js',
            dest: cfg.copyPath,
        },
        {
            src: 'src/lib/LayoutCal_mod.js',
            dest: cfg.copyPath,
        },
        {
            src: 'src/lib/wasm_loader.js',
            dest: cfg.copyPath,
        },
        {
            src: 'src/lib/LayoutCal.wasm',
            dest: cfg.copyPath,
        },
        {
            src: 'dist/main.js',
            dest: cfg.copyPath
        },
        {
            src: 'dist/main.js.map',
            dest: cfg.copyPath,
            rename: name => name + '.map.js',
            transform: contents => `module.exports = ${contents.toString()};`
        }
    ],
    hook: 'writeBundle',
    verbose: true
}) :
// 更新 .map 到 .map.js 并上传
screeps({config: cfg,dryRun: !cfg})

export default {
  input: "src/main.ts",
  output: {
    // dir: 'output',
    file: "dist/main.js",
    format: "cjs",
    sourcemap: true
  },
  external: [
    path.resolve( './src/lib/Analysis.js' ),
     path.resolve( './src/lib/wasm_loader.js' ),
     path.resolve( './src/lib/LayoutCal_mod.js' ),
  ],
  plugins: [
    clear({ targets: ["dist"] }),
    resolve({ rootDir: "src" }),
    commonjs(),
    wasm(),
    typescript({tsconfig: "./tsconfig.json"}),
    pluginDeploy,
    // copy({
    //   targets:
    //     [{
    //       src: 'src/lib/LayoutCal_mod.js',
    //       dest: 'dist'
    //     },
    //     {
    //       src: 'src/lib/wasm_loader.js',
    //       dest: 'dist'
    //     },
    //     {
    //       src: 'src/lib/LayoutCal.wasm',
    //       dest: 'dist'
    //       }],
    //     verbose: true
    //   }
    // ),
//    screeps({config: cfg,dryRun: !cfg})
  ]
}
